package com.smzd.ccms.business;

import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.smzd.ccms.dao.CompletParamConfigDao;
import com.smzd.ccms.dao.CompletParamDao;
import com.smzd.ccms.domain.CompletConfig;
import com.smzd.ccms.domain.CompletParam;
import com.smzd.ccms.domain.CompletParamConfig;
import com.smzd.ccms.domain.Dict;
import com.smzd.core.dao.IDao;
import com.smzd.framework.core.business.AbstractFGService;
import com.smzd.framework.utils.JsonHelper;
import com.smzd.framework.utils.db.FGRowConverter;
import com.smzd.framework.utils.db.RPage;

@Service
public class CompletParamConfigService extends AbstractFGService<CompletParamConfig> {
    @Autowired
    private CompletParamConfigDao dao;
    @Autowired
    private CompletParamDao cpDao;
    
    @Override
    protected IDao<CompletParamConfig> getDao() {
        return dao;
    }
    
    @Override
    public FGRowConverter<CompletParamConfig> getConverter() {
        return converter;
    }

    private static FGRowConverter<CompletParamConfig> converter = new FGRowConverter<CompletParamConfig>() {
        @Override
        public Object[] convert(CompletParamConfig elem) {
            Object[] fs = new Object[]{
                    elem.getId(),
                    elem.getName(),
                    elem.getKey(),
                    elem.getDescription(),
                    elem.getValue(),
                    elem.getType()
                };
                return fs;
        }
    };


    private static FGRowConverter<Dict> dictconverter = new FGRowConverter<Dict>() {
        @Override
        public Object[] convert(Dict elem) {
            Object[] fs = new Object[]{
                    elem.getId(),
                    elem.getName(),
                    elem.getDescription(),
                    elem.getKey(),
                    elem.getAlias(),
                    elem.getType(),
                    elem.getSource(),
                    elem.getValue(),
                    elem.getOldValue(),
                    StringUtils.isNotEmpty(elem.getOldValue())
                };
                return fs;
        }
    };
	public String getAllParamsConfigInJsonString(CompletConfig ccfg) {
		List<Dict> elems = dao.getCompletParamsByCompletConfig(ccfg);
		List<Dict> all = new ArrayList<>();
		//新的参数配置
		for(Dict dict : elems){
			if(dict.getId()>0){
				all.add(dict);
			}
		}
		//把原始的配置加入进去
		for(Dict e : elems){
			if(e.getId()<0){
				boolean found = false;
				for(Dict n : all){
					if(n.getKey().equalsIgnoreCase(e.getKey())){
						n.setOldValue(e.getValue());
						found = true;
						break;
					}
				}
				if(!found){
					e.setOldValue(e.getValue());
					e.setValue(null);
					all.add(e);
				}
			}
		}
		
		RPage<Dict> page = new RPage<>();
		page.setElems(all);
		int totalCount = all.size();
		page.setTotalCount(totalCount);
		page.setPageSize(totalCount);
		return page.toFlexiGridJsonString(dictconverter);
	}

	public String customizeParamValue(CompletConfig cconfig, int paramId, String value, String alias, int source) throws Exception {
		//首先要检查该配置是否进行过，是否进行过配置只需要通过检验paramId就可以了。
		//如果配置过，paramId是正数，含义为CompletParamConfig.id，否则是负数，含义为对应的CompletParam.id
		if(paramId<0){//提交上来原始参数的ID来了，说明这个参数没有配置过。
			paramId = -paramId;
			CompletParam cp = cpDao.getElemById(paramId);
			if(cp==null){
				throw new Exception("要配置的参数不存在！");
			}
			if(cp.getScope().getId()-cconfig.getComplet().getId()!=0){
				throw new Exception("要配置的参数不正确！");
			}
			CompletParamConfig cpc = dao.getCompletParamConfigByScopeKey(cconfig, cp.getKey());
			if(cpc!=null){
				cpc.setAlias(alias);
				cpc.setValue(value);
				cpc.setType(cp.getType());
				cpc.setSource(source);
				dao.updateValue(cpc);
			}else{
				cpc = new CompletParamConfig(cp);
				cpc.setAlias(alias);
				cpc.setScope(cconfig);
				cpc.setValue(value);
				cpc.setSource(source);
				dao.insert(cpc);
			}
		}else{//以前配置过，直接拿出来配置一下就行了
			CompletParamConfig cpc = dao.getElemById(paramId);
			if(cpc==null){
				throw new Exception("要配置的参数不存在!");
			}
			if(cpc.getScope().getId()-cconfig.getId()!=0){
				throw new Exception("要配置的参数不正确！");
			}
			cpc.setAlias(alias);
			cpc.setValue(value);
			cpc.setSource(source);
			dao.updateValue(cpc);
		}
		return JsonHelper.getSuccessJsonString();
	}

	public String restoreParamValue(CompletConfig cconfig, int paramId) throws Exception {
		if(paramId<0){
			throw new Exception("该参数配置无法恢复！没有配置过！");
		}
		CompletParamConfig cpc = dao.getElemById(paramId);
		if(cpc==null){
			throw new Exception("要配置的参数不存在!");
		}
		if(cpc.getScope().getId()-cconfig.getId()!=0){
			throw new Exception("要配置的参数不正确！");
		}
		dao.disableCompletParamConfig(cpc);
		return JsonHelper.getSuccessJsonString();
	}
    
}